import React, { ReactElement, useState } from 'react';
import { View, Text, Image, ScrollView } from 'react-native';
import { BoxShadow as SVGShadow } from 'react-native-shadow';

import styles, { MAX_CONTENT_HEIGHT } from './style';
import Button from '../Button';
import { closeSelect, optionSelected } from '../../constant/resource';
import { modalClose } from '../../util/global';
import { isIOS } from '../../constant';
import { px } from '../../util/adapt';

export interface OptionProps {
  id: number;
  desc: string;
}

interface SelectProps {
  title: string;
  options: OptionProps[];
  currentId: number;
  action: (id: number) => void;
}

interface ItemProps extends OptionProps {
  isSelected: boolean;
}

export default ({
  title,
  options,
  currentId,
  action
}: SelectProps): ReactElement => {
  const [selectedId, setSelectedId] = useState(currentId);
  const [height, setHeight] = useState(0);

  const shadowOpt = {
    width: px(300),
    height: height + px(96),
    color: '#00336B',
    border: px(12),
    radius: px(4),
    opacity: 0.15,
    x: 0,
    y: 0
  };

  const Item = (props: ItemProps): ReactElement => {
    const { id, desc, isSelected } = props;

    if (isSelected) {
      return (
        <View style={[styles.item, styles.selectedItem]}>
          <Text style={styles.selectedDesc}>{desc}</Text>
          <Image style={styles.selectedIcon} source={optionSelected} />
        </View>
      );
    }

    return (
      <Button
        style={[styles.item, styles.unSelectedItem]}
        onPress={(): void => {
          setSelectedId(id);
          action(id);
        }}
      >
        <Text style={styles.desc}>{desc}</Text>
      </Button>
    );
  };

  const Content = (): ReactElement => {
    return (
      <View style={[styles.container, isIOS ? styles.shadowContainer : {}]}>
        <Text style={styles.title}>{title}</Text>
        <Button
          hitSlop={{ left: 20, top: 20, right: 20, bottom: 20 }}
          style={styles.close}
          onPress={modalClose}
        >
          <Image style={styles.closeIcon} source={closeSelect} />
        </Button>

        <ScrollView
          style={styles.scrollView}
          contentContainerStyle={styles.content}
          onContentSizeChange={(contentWidth, contentHeight): void => {
            setHeight(
              contentHeight > MAX_CONTENT_HEIGHT
                ? MAX_CONTENT_HEIGHT
                : contentHeight
            );
          }}
        >
          {options.map(
            (item): ReactElement => (
              <Item {...item} isSelected={item.id === selectedId} />
            )
          )}
        </ScrollView>
      </View>
    );
  };

  if (isIOS || height === 0) {
    return <Content />;
  }

  return (
    <SVGShadow setting={shadowOpt}>
      <Content />
    </SVGShadow>
  );
};
